#ifndef _TASK_H_
#define _TASK_H_

#include "def.h"
#include <pthread.h>
#include <signal.h>


#ifdef __cplusplus
extern "C"{
#endif

#define TASK_NAME_MAX_SIZE  16

typedef struct task {
    char tname[TASK_NAME_MAX_SIZE];
    pthread_t tid;
    thread_func tfunc;
    void *targ;
}task_t;

static inline int task_init(task_t *self, const char *name, thread_func func, void *arg)
{
    strncpy(self->tname, name, TASK_NAME_MAX_SIZE);
    self->tfunc = func;
    self->targ = arg;
    self->tid = -1;

    if(pthread_create(&self->tid, NULL, func, arg) != 0){
        ERR("pthread_create failed");
        return -1;
    }

    return 0;
}

static inline void task_cancel(task_t *self)
{
    if (self->tid != -1)
        pthread_cancel(self->tid);
}

static inline void task_term(task_t *self)
{
    if (self->tid != -1)
        pthread_join(self->tid, NULL);
}

static inline const char *task_name(task_t *self)
{
    return self->tname;
}

static inline pthread_t task_tid(task_t *self)
{
    return self->tid;
}

static inline void *task_arg(task_t *self)
{
    return self->targ;
}

#ifdef __cplusplus
}
#endif

#endif
